import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.util.*;
import java.io.FileWriter;
import java.io.IOException;
import java.io.BufferedWriter;
import java.time.format.DateTimeFormatter;
import java.time.Duration;
import java.time.ZoneId;
import java.util.stream.Collectors;
import java.time.DayOfWeek;
import java.time.Instant;
public class CinemaManagementSystem {
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd HH:mm");//日期格式化
    private static Scanner scanner = new Scanner(System.in);
    private static List<Screening> screenings = new ArrayList<>();//存储所有放映场次
    private static List<Ticket>soldTickets=new ArrayList<>();//存储已售门票
    private static Admin rootAdmin = new Admin("admin", "admin", "ynuinfo#777", new Date(), "12345678901");
    private static User currentUser = null;
    private static Movie testMovie = new Movie("M000", "测试影片", "新导演", "新演员", "新剧情", 100, 7.5);
    private static Screening testScreening;
    private static Seat testSeat1 = new Seat(Integer.parseInt("01"), Integer.parseInt("01"));
    private static Seat testSeat2 = new Seat(Integer.parseInt("02"), Integer.parseInt("10"));
    private static Manager manager = new Manager("M001", "manager", "123456", new Date(), "12345678902");
    private static Movie movie1 = new Movie("M001", "哪吒之魔童降世", "饺子", "吕艳婷, 囱, 瀚墨, 陈浩", "该片讲述了本应是灵珠转世的哪吒却因阴谋被魔丸附体，自出生起就被百姓畏惧。在三年寿命的倒计时中，他打破命运偏见，逆天改命，最终成为英雄的热血故事。", 110, 8.4);
    private static Movie movie2 = new Movie("M002", "星际穿越", "克里斯托弗·诺兰", "马修·麦康纳, 安妮·海瑟薇", "一部科幻电影，讲述了人类在地球上面临生存危机时，一群宇航员通过虫洞寻找新家园的故事。", 169, 9.2);
    private static Movie movie3 = new Movie("M003", "泰坦尼克号", "詹姆斯·卡梅隆", "莱昂纳多·迪卡普里奥, 凯特·温斯莱特", "影片以1912年泰坦尼克号邮轮在其处女航时触礁冰山而沉没的事件为背景，讲述了处于不同阶层的两个人穷画家杰克和贵族女露丝抛弃世俗的偏见坠入爱河，最终杰克把生命的机会让给了露丝的感人故事。", 195, 9.4);
    private static Movie movie4 = new Movie("M004", "肖申克的救赎", "弗兰克·德拉邦特", "蒂姆·罗宾斯, 摩根·弗里曼", "该片改编自斯蒂芬·金的同名小说，讲述了一个银行家在被冤枉入狱后，与狱友建立深厚友谊并最终重获自由的故事。", 142, 9.7);
    private static Movie movie5 = new Movie("M005", "这个杀手不太冷", "吕克·贝松", "让·雷诺, 娜塔莉·波特曼", "该片讲述了一名职业杀手在接到一个刺杀少女家人任务后，对少女产生恻隐之心，并在刺杀任务完成后，承担起照顾少女责任的故事。", 110, 9.4);
    private static FrontDesk currentFrontDesk = new FrontDesk("F001", "front" + "desk", "123456", new Date(), "12345678903");

    static {
        Manager manager = new Manager("M001", "manager", "123456", new Date(), "12345678902");
        FrontDesk frontDesk = new FrontDesk("F001", "front" + "desk", "123456", new Date(), "12345678903");
        testScreening = new Screening("S001", testMovie, "1号厅", new Date(System.currentTimeMillis() + 3600000 * 2), 50.0);
        Movie testMovie = new Movie("M000", "测试影片", "测试导演", "测试演员", "测试简介", 180, 7.5);
        Screening testScreening = new Screening("S001", testMovie, "1号厅", new Date(), 50.0);
        Calendar cal = Calendar.getInstance();
        Calendar c1 = (Calendar) cal.clone();
        c1.set(Calendar.HOUR_OF_DAY, 23);
        c1.set(Calendar.MINUTE, 0);
        c1.set(Calendar.SECOND, 0);
        c1.set(Calendar.MILLISECOND, 0);
        Date time1 = c1.getTime();
        Calendar c2 = (Calendar) cal.clone();
        c2.add(Calendar.DAY_OF_MONTH, 1);
        c2.set(Calendar.HOUR_OF_DAY, 14);
        c2.set(Calendar.MINUTE, 0);
        c2.set(Calendar.SECOND, 0);
        Date time2 = c2.getTime();
        Calendar c3 = (Calendar) cal.clone();
        c3.add(Calendar.DAY_OF_MONTH, 1);
        c3.set(Calendar.HOUR_OF_DAY, 20);
        c3.set(Calendar.MINUTE, 0);
        c3.set(Calendar.SECOND, 0);
        Date time3 = c3.getTime();
        Calendar c4 = (Calendar) cal.clone();
        c4.add(Calendar.DAY_OF_MONTH, 2);
        c4.set(Calendar.HOUR_OF_DAY, 15);
        c4.set(Calendar.MINUTE, 0);
        c4.set(Calendar.SECOND, 0);
        Date time4 = c4.getTime();
        Calendar c5 = (Calendar) cal.clone();
        c5.add(Calendar.DAY_OF_MONTH, 2);
        c5.set(Calendar.HOUR_OF_DAY, 21);
        c5.set(Calendar.MINUTE, 0);
        c5.set(Calendar.SECOND, 0);
        Date time5 = c5.getTime();
        Screening screening1 = new Screening("S001", movie1, "1号厅", time1, 50.0);
        List<List<Seat>> seatRows1 = screening1.createSeatsForHall(1);
        List<Seat> seats1 = seatRows1.stream().flatMap(row -> row.stream()).collect(Collectors.toList());
        screening1.setSeats(seats1);
        Screening screening2 = new Screening("S002", movie2, "2号厅", time2, 50.0);
        List<List<Seat>> seatRows2 = screening2.createSeatsForHall(2);
        List<Seat> seats2 = seatRows2.stream().flatMap(row -> row.stream()).collect(Collectors.toList());
        screening2.setSeats(seats2);
        Screening screening3 = new Screening("S003", movie3, "3号厅", time3, 50.0);
        List<List<Seat>> seatRows3 = screening3.createSeatsForHall(3);
        List<Seat> seats3 = seatRows3.stream().flatMap(row -> row.stream()).collect(Collectors.toList());
        screening3.setSeats(seats3);
        Screening screening4 = new Screening("S004", movie4, "4号厅", time4, 50.0);
        List<List<Seat>> seatRows4 = screening4.createSeatsForHall(4);
        List<Seat> seats4 = seatRows4.stream().flatMap(row -> row.stream()).collect(Collectors.toList());
        screening4.setSeats(seats4);
        Screening screening5 = new Screening("S005", movie5, "5号厅", time5, 50.0);
        List<List<Seat>> seatRows5 = screening5.createSeatsForHall(5);
        List<Seat> seats5 = seatRows5.stream().flatMap(row -> row.stream()).collect(Collectors.toList());
        screening5.setSeats(seats5);
        manager.addScreening(screening1);//添加场次到经理
        manager.addScreening(screening2);
        manager.addScreening(screening3);
        manager.addScreening(screening4);
        manager.addScreening(screening5);
        currentFrontDesk.addScreening(screening1);//添加场次到前台
        currentFrontDesk.addScreening(screening2);
        currentFrontDesk.addScreening(screening3);
        currentFrontDesk.addScreening(screening4);
        currentFrontDesk.addScreening(screening5);
        rootAdmin.addUser(rootAdmin);//管理员添加用户
        rootAdmin.addUser(manager);
        rootAdmin.addUser(frontDesk);
        //Manager manager=(Manager) rootAdmin.getUser("M001");
        rootAdmin.addUser(rootAdmin);
        if (manager != null) {
            manager.addMovie(movie1);
            manager.addMovie(movie2);
            manager.addMovie(movie3);
            manager.addMovie(movie4);
            manager.addMovie(movie5);
        } else {
            System.out.println("无效选择！");
        }
        if (currentFrontDesk != null) {
            currentFrontDesk.addMovie(movie1);
            currentFrontDesk.addMovie(movie2);
            currentFrontDesk.addMovie(movie3);
            currentFrontDesk.addMovie(movie4);
            currentFrontDesk.addMovie(movie5);
        } else {
            System.out.println("无效选择！");
        }
    }
    private static boolean isValidScope(String scpoe){//判断scope是否为null或空字符串
        return scpoe!=null||scpoe.trim().isEmpty();
    }
    private static void scheduleScreening(Manager manager, Movie movie, String cinemaRoom, Date showTime) {//自动调度场次
        String screeningId = "SC-" + movie.getMovieId() + "-" + System.currentTimeMillis();
        Screening screening = new Screening(screeningId, movie, cinemaRoom, showTime, 50.0);
        manager.addScreening(screening);
        System.out.println("已为《" + movie.getTitle() + "》排场次：" + screeningId);
    }
    public class LoggerUtil {
        private static final String LOG_FILE_PATH = "cinema_log.txt";
        private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        public static void log(String content) {
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(LOG_FILE_PATH, true))) {
                writer.write(sdf.format(new Date()) + " - " + content);
                writer.newLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public static List<Screening> getScreeningsByMovie(Movie movie) {
        List<Screening> result = new ArrayList<>();
        for (Screening s : screenings) {
            if (s.getMovie().equals(movie)) {
                result.add(s);
            }
        }
        return result;
    }
    public static void main(String[] args) {
        System.out.println("=== 影院管理系统 v1.0 ===");
        while (true) {
            if (currentUser == null) {
                showLoginMenu();
                String choice = scanner.nextLine().trim();
                if ("3".equals(choice)) {
                    System.out.println("系统已退出，再见！");
                    break;
                }
                handleLogin(choice);
            } else {
                showMainMenu();
                String choice = scanner.nextLine().trim();
                if ("0".equals(choice)) {
                    currentUser = null;
                    System.out.println("已退出登录");
                } else {
                    handleUserChoice(choice);
                }
            }
        }
        scanner.close();
    }
    private static void showLoginMenu() {
        System.out.println("\n=== 登录入口 ===");
        System.out.println("1. 管理员登录");
        System.out.println("2. 员工登录（经理/前台）");
        System.out.println("3. 退出系统");
        System.out.print("请选择：");
    }
    private static void handleLogin(String choice) {
        System.out.print("请输入用户名：");
        String username = scanner.nextLine().trim();
        System.out.print("请输入密码：");
        String password = scanner.nextLine().trim();

        if ("1".equals(choice)) {
            if ("admin".equals(username) && "ynuinfo#777".equals(password)) {
                currentUser = rootAdmin;
                System.out.println("管理员登录成功！");
                showMainMenu();
            } else {
                System.out.println("管理员用户名或密码错误！");
            }
        } else if ("2".equals(choice)) {
            User user = rootAdmin.queryUserByUsername(username);
            if (user != null && user.getPassword().equals(password)) {
                currentUser = user;
                System.out.println(user.getUserType() + " 登录成功！");
                showMainMenu();
            } else {
                System.out.println("员工用户名或密码错误！");
            }
        } else {
            System.out.println("无效选项，请重新选择！");
        }
    }
    private static void showMainMenu() {
        System.out.println("\n=== 主菜单 ===");
        if (currentUser instanceof Admin) {
            System.out.println("1. 密码管理");
            System.out.println("2. 用户管理");
            System.out.println("0. 退出登录");
        } else if (currentUser instanceof Manager) {
            System.out.println("1. 密码管理");
            System.out.println("2. 影片管理");
            System.out.println("3. 排片管理");
            System.out.println("4. 查看销售数据");
            System.out.println("0. 退出登录");
        } else if (currentUser instanceof FrontDesk) {
            System.out.println("1. 列出所有正在上映影片信息");
            System.out.println("2. 列出所有场次信息");
            System.out.println("3. 列出指定电影和场次信息");
            System.out.println("4. 售票功能");
            System.out.println("5. 退票功能");
            System.out.println("0. 退出登录");
        }
        System.out.print("请选择功能：");
    }
    private static void handleUserChoice(String choice) {
        if (currentUser instanceof Admin) {
            handleAdminChoice(choice);
        } else if (currentUser instanceof Manager) {
            handleManagerChoice(choice);
        } else if (currentUser instanceof FrontDesk) {
            handleFrontDeskChoice(choice);
        }
    }
    private static void handleAdminChoice(String choice) {
        Admin admin = (Admin) currentUser;
        switch (choice) {
            case "1":
                System.out.println("\n=== 密码管理 ===");
                System.out.println("1. 修改自身密码 2. 重置非管理员密码");
                System.out.print("子功能选择：");
                String subChoice = scanner.nextLine().trim();
                if ("1".equals(subChoice)) {
                    System.out.println("请输入新密码：");
                    String newPwd = scanner.nextLine().trim();
                    admin.setPassword(newPwd);
                    ;
                    System.out.println("自身密码修改成功");
                    String logContent = String.format("操作类型：修改管理员密码，操作人：XX，修改时间：XXXX.XX.XX", admin.getUsername(), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                    LoggerUtil.log(logContent);
                } else if ("2".equals(subChoice)) {
                    System.out.println("请输入重置密码的用户名：");
                    String username = scanner.nextLine().trim();
                    User user = admin.queryUser(username);
                    if (user == null) {
                        System.out.println(" 用户不存在！");
                    } else if ("admin".equals(user.getUserType().toString().toLowerCase())) {
                        System.out.println(" 不允许重置管理员（admin）类型的用户密码！");
                    } else {
                        user.setPassword("123456");
                        System.out.println(" 密码已重置为 123456，请通知该用户登录后修改。");
                        String logContent = String.format("操作类型：重置非管理员XX密码，操作人：XX,重置时间：XXXX.XX.XX", user.getUserType(), username, admin.getUsername(), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                        LoggerUtil.log(logContent);
                    }

                }
                break;
            case "2":
                System.out.println("\n===用户管理===");
                System.out.println("1.列出所有用户信息 2.删除指定用户信息 3.查询用户信息 4.增加用户信息 5.修改用户信息");
                String subChoiceUser = scanner.nextLine().trim();
                if ("1".equals(subChoiceUser)) {
                    List<User> users = admin.listAllUsers();
                    if (users.isEmpty()) {
                        System.out.println("暂无用户信息");
                        break;
                    }
                    users.forEach(user -> System.out.println("ID" + user.getUserId() + "用户名称" + user.getUsername() + "类型：" + user.getUserType() + "注册时间" + user.getRegisterTime()));
                    break;
                } else if ("2".equals(subChoiceUser)) {
                    System.out.println("请输入要删除的用户名：");
                    String delUsername = scanner.nextLine().trim();
                    User delUser = admin.queryUser(delUsername);
                    if (delUser == null) {
                        System.out.println("用户不存在！");
                        break;
                    }
                    String warning = "警告：删除用户 [" + delUser.getUsername() + "] 操作不可逆，是否继续？(y/n)";
                    if ("admin".equals(delUser.getUsername())) {
                        warning = "警告：不能删除 admin 管理员账户！（若强制删除需联系超级管理员，输入 y 确认风险操作）";
                    }
                    System.out.println(warning);
                    String confirm = scanner.nextLine().trim();
                    if (!"y".equalsIgnoreCase(confirm)) {
                        System.out.println("取消删除操作");
                        break;
                    }
                    if ("admin".equals(delUser.getUsername())) {
                        System.out.println("操作失败：admin 管理员账户不可删除！");
                        break;
                    }
                    admin.removeUser(delUser);
                    System.out.println("用户删除成功");
                    try {
                        String logContent = "\n[删除操作] " + "时间：" + new Date() + "，操作类型：删除用户" + "，用户名：" + delUser.getUsername() + "，操作人：XX";
                        FileWriter writer = new FileWriter("operation_log.txt", true);
                        writer.write(logContent);
                        writer.close();
                        System.out.println("操作已记录到日志文件");
                    } catch (IOException e) {
                        System.out.println("日志记录失败：" + e.getMessage());
                    }
                    break;
                } else if ("3".equals(subChoiceUser)) {
                    System.out.println("请输入要查询的用户名：");
                    String queryName = scanner.nextLine();
                    User queryUser = admin.queryUser(queryName);
                    List<User> userList = admin.listAllUsers();
                    if (userList.isEmpty()) {
                        System.out.println("暂无用户信息");
                    } else {
                        System.out.println("查询结果：");
                        System.out.println("ID" + queryUser.getUserId() + "用户名" + queryUser.getUsername() + "类型" + queryUser.getUserType() + "注册时间" + queryUser.getRegisterTime());
                    }
                    break;
                } else if ("4".equals(subChoiceUser)) {
                    System.out.print("请输入新增用户ID：");
                    String newId = scanner.nextLine().trim();
                    System.out.print("请输入新增用户名：");
                    String newName = scanner.nextLine().trim();
                    System.out.print("请输入用户类型（Manager/FrontDesk）：");
                    String userType = scanner.nextLine().trim();
                    System.out.println("请输入新用户电话：");
                    String newPhone = scanner.nextLine().trim();
                    if (!"Manager".equals(userType) && !"FrontDesk".equals(userType)) {
                        System.out.println("类型错误，仅支持Manager或FrontDesk");
                        break;
                    }
                    if (admin.queryUser(newName) != null) {
                        System.out.println("用户名已存在");
                        break;
                    }
                    if (admin.queryUserByPhone(newPhone) != null) {
                        System.out.println("手机号已存在");
                        break;
                    }
                    User newUser;
                    if ("Manager".equals(userType)) {
                        newUser = new Manager(newId, newName, "123456", new Date(), newPhone);
                    } else {
                        newUser = new FrontDesk(newId, newName, "123456", new Date(), newPhone);
                    }
                    admin.addUser(newUser);
                    System.out.println("用户添加成功，初始密码为123456");
                    String logContent = String.format("增加时间：XXXX.XX.XX，操作类型：增加XX用户，操作人：XX", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()), userType, newName, admin.getUsername());
                    LoggerUtil.log(logContent);
                    break;
                } else if ("5".equals(subChoiceUser)) {
                    System.out.print("请输入要修改的用户类型：");
                    String editName = scanner.nextLine().trim();
                    User editUser = admin.queryUser(editName);
                    if (editUser == null || "admin".equals(editName)) {
                        System.out.println("用户不存在或不允许修改admin");
                        break;
                    }
                    System.out.println("请输入新用户类型(Manager/FrontDesk)：");
                    String newTypeInput = scanner.nextLine().trim();
                    System.out.println("请输入新手机号：");
                    String newPhone = scanner.nextLine().trim();
                    String upperType = newTypeInput.toUpperCase();
                    String enumName = null;
                    if ("MANAGER".equals(upperType)) {
                        enumName = "MANAGER";
                    } else if ("FRONTDESK".equals(upperType)) {
                        enumName = "FRONTDESK";
                    } else {
                        System.out.println("类型错误，仅支持 Manager 或 FrontDesk");
                        break;
                    }
                    if (admin.queryUserByPhone(newPhone) != null &&
                            !editUser.getPhone().equals(newPhone)) {
                        System.out.println("手机号已存在");
                        break;
                    }
                    editUser.setUserType(UserType.valueOf(enumName));
                    editUser.setPhone(newPhone);
                    System.out.println(" 用户信息修改成功！");
                }
            default:
                System.out.println("无效子功能选择");
        }
    }
    private static void handleManagerChoice(String choice) {
        Manager manager = (Manager) currentUser;
        switch (choice) {
            case "1":
                System.out.println("\n=== 密码管理 ===");
                System.out.println("1. 修改自身密码 2. 重置指定前台用户密码");
                System.out.print("子功能选择：");
                String subChoice = scanner.nextLine().trim();
                if ("1".equals(subChoice)) {
                    System.out.println("请输入新密码：");
                    String newPwd = scanner.nextLine().trim();
                    manager.setPassword(newPwd);
                    System.out.println("自身密码修改成功");
                } else if ("2".equals(subChoice)) {
                    System.out.println("请输入重置密码的用户名：");
                    String username = scanner.nextLine().trim();
                    User user = rootAdmin.queryUser(username);
                    if (user == null) {
                        System.out.println(" 用户不存在！");
                    } else {
                        String targetType = user.getUserType().toString().toLowerCase();
                        if ("admin".equals(targetType) || "manager".equals(targetType)) {
                            System.out.println(" 不允许重置 admin 或 manager 的密码！");
                        } else {
                            user.setPassword("123456");
                            System.out.println(" 密码已重置为 123456，请通知该用户登录后及时修改。");
                            String logContent = String.format("重置时间：XXXX.XX.XX,操作类型：重置XX的密码，操作人：XX", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()), username, manager.getUsername());
                            LoggerUtil.log(logContent);
                        }
                    }
                }
                break;
            case ("2"):
                System.out.println("\n===影片管理===");
                System.out.println("1.列出所有正在上映影片信息 2.添加影片信息 3.修改电影信息 4.删除影片信息 5.查询影片信息");
                System.out.println("子功能选择：");
                String subChoiceMovie = scanner.nextLine().trim();
                if ("1".equals(subChoiceMovie)) {
                    List<Movie> movies = manager.listAllMovies();
                    if (movies.isEmpty()) {
                        System.out.println("暂无影片信息");
                    } else {
                        System.out.println("===所有正在上映的电影信息===");
                        for (Movie movie : movies) {
                            System.out.println("ID: " + movie.getMovieId() + ", Title: " + movie.getTitle() + ", Director: " + movie.getDirector() + ",Actors" + movie.getActors() + ",Intro" + movie.getIntro() + ",Duration" + movie.getDuration() + ",Score" + movie.getScore());
                        }
                    }
                } else if ("2".equals(subChoiceMovie)) {
                    System.out.print("请输入影片ID：");
                    String movieId = scanner.nextLine().trim();
                    System.out.print("请输入片名：");
                    String title = scanner.nextLine().trim();
                    System.out.print("请输入导演：");
                    String director = scanner.nextLine().trim();
                    System.out.print("请输入主演：");
                    String actors = scanner.nextLine().trim();
                    System.out.print("请输入剧情简介：");

                    String intro = scanner.nextLine().trim();
                    System.out.print("请输入时长（分钟）：");
                    int duration = Integer.parseInt(scanner.nextLine().trim());
                    System.out.print("请输入评分（0-10）：");
                    double score = Double.parseDouble(scanner.nextLine().trim());
                    Movie newMovie = new Movie("", title, director, actors, intro, duration, score);
                    manager.addMovie(newMovie);
                    System.out.println("已添加新影片：" + newMovie.getMovieId());
                } else if ("3".equals(subChoiceMovie)) {
                    System.out.println("请输入要修改的电影Id：");
                    String movieId = scanner.nextLine().trim();
                    Movie targetMovie = manager.findMovieById(movieId);
                    if (targetMovie != null) {
                        System.out.print("请输入新片名：");
                        String newTitle = scanner.nextLine().trim();
                        if (!newTitle.isEmpty()) {
                            targetMovie.setTitle(newTitle);
                        }
                        System.out.print("请输入新导演：");
                        String newDirector = scanner.nextLine().trim();
                        if (!newDirector.isEmpty()) {
                            targetMovie.setDirector(newDirector);
                        }
                        System.out.println("影片信息修改成功");
                    } else {
                        System.out.println("影片不存在");
                    }
                } else if ("4".equals(subChoiceMovie)) {
                    System.out.print("请输入要删除的影片ID：");
                    String movieId = scanner.nextLine().trim();
                    Movie targetMovie = manager.findMovieById(movieId);
                    if (targetMovie != null) {
                        boolean isShowing = manager.hasScreening(targetMovie);
                        if (isShowing) {
                            System.out.println("影片正在上映，不允许删除");
                        } else {
                            System.out.print("删除后无法恢复，是否确认删除？(y/n)：");
                            String confirm = scanner.nextLine().trim();
                            if ("y".equalsIgnoreCase(confirm)) {
                                manager.deleteMovie(targetMovie);
                                System.out.println("影片删除成功");
                            } else {
                                System.out.println("取消删除操作");
                            }
                        }
                    } else {
                        System.out.println("影片不存在");
                    }
                } else if ("5".equals(subChoiceMovie)) {
                    System.out.print("请输入查询关键词（片名/导演/主演）：");
                    String keyword = scanner.nextLine().trim();
                    List<Movie> resultMovies = manager.searchMovies(keyword);
                    if (resultMovies.isEmpty()) {
                        System.out.println("未找到该影片");
                    } else {
                        resultMovies.forEach(movie -> System.out.println("片号：" + movie.getMovieId() + "，片名：" + movie.getTitle() + "，导演：" + movie.getDirector()));
                    }
                } else {
                    System.out.println("无效子功能选择，请重新输入");
                }
                break;

            default:
                System.out.println("无效功能选择，请重新输入");

            case ("3"):
                System.out.println("\n=== 排片管理===");
                System.out.println("1. 增加场次 2. 修改场次 3.删除场次 4.列出所有场次信息 5.自动排片功能");
                System.out.print("子功能选择：");
                String subChoiceTicket = scanner.nextLine().trim();
                if ("1".equals(subChoiceTicket)) {
                    System.out.print("请输入影片ID（如：M001）：");
                    String movieId = scanner.nextLine().trim();
                    Movie targetMovie = manager.findMovieById(movieId);
                    if (targetMovie == null) {
                        System.out.println("影片不存在！");
                        break;
                    }
                    System.out.print("请输入放映厅（如：1号厅）：");
                    String cinemaRoom = scanner.nextLine().trim();
                    System.out.print("请输入放映时间（格式：yyyy-MM-dd HH:mm）：");
                    Date showTime = null;
                    try {
                        showTime = sdf.parse(scanner.nextLine().trim());
                    } catch (Exception e) {
                        System.out.println("时间格式错误！");
                        break;
                    }
                    System.out.print("请输入该场次票价：");
                    double price = Double.parseDouble(scanner.nextLine().trim());
                    String screeningId = movieId + "_" + System.currentTimeMillis();
                    Screening newScreening = new Screening(screeningId, targetMovie, cinemaRoom, showTime, price);
                    manager.addScreening(newScreening);
                    System.out.println("已添加场次：" + screeningId);
                    break;
                } else if ("2".equals(subChoiceTicket)) {
                    System.out.print("请输入需要修改的场次ID：");
                    String screeningId = scanner.nextLine().trim();
                    Screening targetScreening = manager.findScreeningById(screeningId);
                    if (targetScreening == null) {
                        System.out.println("场次不存在！");
                        break;
                    }
                    if (targetScreening.hasSoldTickets()) {
                        System.out.println("该场次已有售票，不允许修改！");
                        break;
                    }
                    System.out.print("请输入新的影片ID（如：M001）：");
                    String newMovieId = scanner.nextLine().trim();
                    Movie newTargetMovie = manager.findMovieById(newMovieId);
                    if (newTargetMovie == null) {
                        System.out.println("新影片不存在！");
                        break;
                    }
                    System.out.print("请输入新的放映厅（如：1号厅）：");
                    String newCinemaRoom = scanner.nextLine().trim();
                    System.out.print("请输入新的放映时间（格式：yyyy-MM-dd HH:mm）：");
                    Date newShowTime = null;
                    try {
                        newShowTime = sdf.parse(scanner.nextLine().trim());
                    } catch (Exception e) {
                        System.out.println("时间格式错误！");
                        break;
                    }
                    System.out.print("请输入新的该场次票价：");
                    double newPrice = Double.parseDouble(scanner.nextLine().trim());
                    String originalMovieTitle = targetScreening.getMovie().getTitle();
                    String newMovieTitle = newTargetMovie.getTitle();
                    String operator = manager.getUsername();
                    targetScreening.setMovie(newTargetMovie);
                    targetScreening.setCinemaHall(newCinemaRoom);
                    targetScreening.setTime(newShowTime);
                    targetScreening.setPrice(newPrice);
                    String logContent = String.format("修改时间：XXXX.XX.XX,操作类型：修改场次信息（场次时间：XXXX.XX.XX,原片名：XX，新片名：XX），操作人：XX", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()), targetScreening.getTime(), originalMovieTitle, newMovieTitle, operator);
                    LoggerUtil.log(logContent);
                    System.out.println("已修改场次：" + screeningId);
                    break;
                } else if ("3".equals(subChoiceTicket)) {
                    System.out.print("请输入需要删除的场次ID：");
                    String screeningId = scanner.nextLine().trim();
                    Screening targetScreening = manager.findScreeningById(screeningId);
                    if (targetScreening == null) {
                        System.out.println("场次不存在！");
                    } else if (targetScreening.hasSoldTickets()) {
                        System.out.println("该场次已有售票，不允许删除！");
                    }
                    manager.deleteScreening(targetScreening);
                    manager.logOperation("删除场次", "时间：" + sdf.format(new Date()) + "，场次ID：" + screeningId + "，影片：" + targetScreening.getMovie().getTitle());
                    String movieTitle = targetScreening.getMovie().getTitle();
                    String operator = manager.getUsername();
                    manager.deleteScreening(targetScreening);
                    String logContent = String.format("删除时间：XXXX.XX.XX,操作类型：删除场次信息（场次时间：XXXX.XX.XX,片名：XX），操作人：", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()), targetScreening.getTime(), movieTitle, operator);
                    LoggerUtil.log(logContent);
                    System.out.println("场次删除完成！");
                    break;
                } else if ("4".equals(subChoiceTicket)) {
                    System.out.println("请选择查询范围（week/today/3days）：");
                    String scope = scanner.nextLine().trim();
                    System.out.println("\n=== 场次列表（" + scope + "）===");
                    List<Screening> result = manager.listScreeningsByScope(scope);
                    if (result.isEmpty()) {
                        System.out.println("无匹配场次");
                    } else {
                        for (Screening s : result) {
                            System.out.println("场次ID：" + s.getScreeningId() + "，影片：" + s.getMovie().getTitle() + "，时间：" + sdf.format(s.getTime()) + "，放映厅：" + s.getCinemaHall());
                        }
                    }
                    break;
                } else if ("5".equals(subChoiceTicket)) {
                    manager.autoArrangeScreenings();
                    System.out.println("自动排片完成！已优先为高分影片分配黄金时段。");
                    break;
                } else if ("0".equals(subChoiceTicket)) {
                    break;
                } else {
                    System.out.println("无效选择，请重新输入！");
                }
            case "4":
                System.out.println("\n===查看销售数据===");
                System.out.println("1.查看当日销售数据 2.查看当周销售数据 3.查看当月销售数据");
                System.out.print("子功能选择：");
                String subChoiceDate = scanner.nextLine().trim();
                LocalDate today = LocalDate.now();
                LocalDate startDate = null;
                LocalDate endDate = today;
                String scopeTitle = "";
                if ("1".equals(subChoiceDate)) {
                    startDate = today;
                    scopeTitle = "当日";
                } else if ("2".equals(subChoiceDate)) {
                    startDate = today.with(DayOfWeek.MONDAY);
                    scopeTitle = "当周";
                } else if ("3".equals(subChoiceDate)) {
                    startDate = today.withDayOfMonth(1);
                    scopeTitle = "当月";
                } else if ("0".equals(subChoiceDate)) {
                    break;
                } else {
                    System.out.println("无效选择，请重新输入！");
                }
                int totalTickets = 0;
                double totalAmount = 0.0;
                int refundTickets = 0;
                double refundAmount = 0.0;
                for (Ticket ticket : soldTickets) {
                    Date buyTime = ticket.getBuyTime();
                    Instant instant = buyTime.toInstant();
                    ZonedDateTime zonedDateTime = instant.atZone(ZoneId.systemDefault());
                    LocalDate buyDate = zonedDateTime.toLocalDate();
                    long startTimestamp = startDate.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli();
                    long endTimestamp = endDate.plusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli();
                    for (Ticket t : soldTickets) {
                        long buyTimestamp = t.getBuyTime().getTime();
                        if (buyTimestamp >= startTimestamp && buyTimestamp < endTimestamp) {
                            totalTickets += t.getTotalTickets();
                            totalAmount += t.getTotalPrice();
                            if (ticket.isRefunded()) {
                                refundTickets += ticket.getRefundTickets();
                                refundAmount += ticket.getRefundAmount();
                            }
                        }
                    }
                }
                System.out.println("\n=== " + scopeTitle + "销售数据 ===");
                System.out.println("统计周期: " + startDate + " 至 " + endDate);
                System.out.println("总售票数: " + totalTickets);
                System.out.println("总销售额: ¥" + String.format("%.2f", totalAmount));
                System.out.println("总退票数: " + refundTickets);
                System.out.println("总退票额: ¥" + String.format("%.2f", refundAmount));
                System.out.println("净销售额: ¥" + String.format("%.2f", (totalAmount - refundAmount)));

        }
    }
    private static void handleFrontDeskChoice(String choice) {
        switch (choice) {
            case "1":
                List<Movie> showingMovies = currentFrontDesk.listShowingMovies();
                List<Movie> movies = currentFrontDesk.listAllShowingMovies();
                if (movies.isEmpty()) {
                    System.out.println("暂无影片信息");
                } else {
                    System.out.println("===所有正在上映的电影信息===");
                    for (Movie movie : movies) {
                        System.out.println("ID: " + movie.getMovieId() + ", Title: " + movie.getTitle() + ", Director: " + movie.getDirector() + ",Actors" + movie.getActors() + ",Intro" + movie.getIntro() + ",Duration" + movie.getDuration() + ",Score" + movie.getScore());
                    }
                }
                break;
            case "2":
                System.out.print("请输入场次范围（week/today/3days）：");
                String scopeFind = scanner.nextLine();
                List<Screening> screenings = currentFrontDesk.listScreenings(scopeFind);
                System.out.println("\n=== 场次信息（" + scopeFind + "）===");
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                for (Screening screening : screenings) {
                    System.out.println("场次ID：" + screening.getScreeningId());
                    System.out.println("影片名称：" + screening.getMovie().getTitle());
                    System.out.println("放映时间：" + sdf.format(screening.getTime()) + "\n");
                }
                break;
            case "3":
                System.out.print("请输入影片名称：");
                String movieName = scanner.nextLine();
                System.out.print("请输入场次ID：");
                String screeningId = scanner.nextLine();
                Screening targetScreening = currentFrontDesk.queryMovieScreeningsByTitle(movieName);
                if (targetScreening == null) {
                    System.out.println("未找到对应场次！");
                } else {
                    List<Seat> allSeats = targetScreening.getSeats();
                    if (allSeats.isEmpty()) {
                        System.out.println("该场次尚未初始化座位信息！");
                        return;
                    }
                    System.out.println(" 影片：" + targetScreening.getMovie().getTitle());
                    System.out.println("厅：" + targetScreening.getCinemaHall());
                    System.out.println("时间：" + targetScreening.getTime());
                    System.out.println("座位图（O=可选，X=已售）：");
                    int maxRow = allSeats.stream().mapToInt(Seat::getRow).max().orElse(0);
                    int maxCol = allSeats.stream().mapToInt(Seat::getCol).max().orElse(0);
                    for (int row = 1; row <= maxRow; row++) {
                        for (int col = 1; col <= maxCol; col++) {
                            int finalRow = row;
                            int finalCol = col;
                            Seat seat = allSeats.stream().filter(s -> s.getRow() == finalRow && s.getCol() == finalCol).findFirst().orElse(null);
                            if (seat == null) {
                                System.out.print("  ");
                            } else if (seat.isOccupied()) {
                                System.out.print("X ");
                            } else {
                                System.out.print("O ");
                            }
                        }
                        System.out.println();
                    }
                    long occupiedCount = allSeats.stream().filter(Seat::isOccupied).count();
                    int totalSeats = allSeats.size();
                    System.out.println("\n总座位数：" + totalSeats + "，已售：" + occupiedCount + "，可选：" + (totalSeats - occupiedCount));
                    for (Seat seat : allSeats) {
                        if (seat.getRow() > maxRow) maxRow = seat.getRow();
                        if (seat.getCol() > maxCol) maxCol = seat.getCol();
                    }
                    System.out.print("    ");
                    for (int col = 1; col <= maxCol; col++) {
                        System.out.printf("%-4d", col);
                    }
                    System.out.println();
                    String[][] seatGrid = new String[maxRow + 1][maxCol + 1];
                    for (int r = 1; r <= maxRow; r++) {
                        for (int c = 1; c <= maxCol; c++) {
                            seatGrid[r][c] = " ";
                        }
                    }
                    for (Seat seat : allSeats) {
                        int row = seat.getRow();
                        int col = seat.getCol();
                        if (row >= 1 && row <= maxRow && col >= 1 && col <= maxCol) {
                            seatGrid[row][col] = seat.isOccupied() ? "X" : "O";
                        }
                    }
                    for (int r = 1; r <= maxRow; r++) {
                        System.out.printf("%-2d ", r);
                        for (int c = 1; c <= maxCol; c++) {
                            System.out.printf("%-4s", seatGrid[r][c]);
                        }
                        System.out.println();
                    }
                }
                break;
            case "4":
                System.out.print("请输入场次ID: ");
                String sellScreeningId = scanner.nextLine();
                Screening targetScreeningSeat = currentFrontDesk.listScreenings().stream().filter(s -> s.getScreeningId().equals(sellScreeningId)).findFirst().orElse(null);
                if (targetScreeningSeat == null) {
                    System.out.println("未找到对应场次！");
                    break;
                }
                List<Seat> allSeats = targetScreeningSeat.getSeats();
                if (allSeats == null || allSeats.isEmpty()) {
                    System.out.println("该场次的座位信息为空或未初始化！");
                    break;
                }
                int maxRows = allSeats.stream().mapToInt(Seat::getRow).max().orElse(0);
                int maxCols = allSeats.stream().mapToInt(Seat::getCol).max().orElse(0);
                System.out.println("当前场次座位布局: " + maxRows + " 行 x " + maxCols + " 列");
                System.out.print("请输入座位号（格式：行 列，多个座位用空格分隔）：");
                String[] seatPairs = scanner.nextLine().split("\\s+");
                List<Seat> selectedSeats = new ArrayList<>();
                boolean hasError = false;
                System.out.print("请输入票ID: ");
                String ticketId = scanner.nextLine();
                for (String pair : seatPairs) {
                    String[] parts = pair.trim().split(",");
                    if (parts.length != 2) {
                        System.out.println("输入格式错误！请使用 '行,列' 格式");
                        hasError = true;
                        continue;
                    }
                    try {
                        int row = Integer.parseInt(parts[0]);
                        int col = Integer.parseInt(parts[1]);
                        if (row < 1 || row > maxRows || col < 1 || col > maxCols) {
                            System.out.println("座位【" + row + "," + col + "】超出范围");
                            hasError = true;
                            continue;
                        }
                        Seat seat = allSeats.stream().filter(s -> s.getRow() == row && s.getCol() == col).findFirst().orElse(null);
                        if (seat == null) {
                            System.out.println("座位【" + row + "," + col + "】不存在！");
                            hasError = true;
                        } else if (seat.isOccupied()) {
                            System.out.println("座位【" + row + "," + col + "】已售出！");
                            hasError = true;
                        } else {
                            seat.setOccupied(true);
                            seat.setTicketId(ticketId);
                            selectedSeats.add(seat);
                            System.out.println("成功选择座位【" + row + "," + col + "】");
                        }
                    } catch (NumberFormatException e) {
                        System.out.println("输入格式错误！请确保行和列都是数字");
                        hasError = true;
                    }
                }
                if (selectedSeats.isEmpty()) {
                    System.out.println("未选择有效座位！");
                    if (hasError) {
                        System.out.println("请检查错误信息后重试");
                    }
                    break;
                }
                int totalTickets=0;
                int refundTickets=0;
                double refunded=0.0;
                double totalPrice = 50.0 * selectedSeats.size();
                Ticket ticket = new Ticket(ticketId, targetScreeningSeat, selectedSeats, selectedSeats.size(), new Date(), totalTickets, totalPrice, refundTickets,refunded );
                ticket.sell(selectedSeats.size(), 50.0);
                System.out.print("请输入查询范围（scope）: ");
                String scope = scanner.nextLine();
                if (isValidScope(scope)) {
                    Ticket saleData = manager.querySaleData(scope);
                } else {
                    System.out.println("查询范围格式错误，请重新输入！");
                }
                Ticket saleData = manager.querySaleData(scope);
                System.out.println("===== 售票成功 =====");
                System.out.println("票号: " + ticketId);
                System.out.println("场次: " + targetScreeningSeat.getScreeningId());
                System.out.println("座位: " + selectedSeats.stream().map(s -> "[" + s.getRow() + "," + s.getCol() + "]").collect(Collectors.joining(", ")));
                System.out.println("总价: " + totalPrice);
                System.out.println("查询范围: " + scope);
                break;
            case "5":
                System.out.print("请输入电子票号：");
                String ownTicketId = scanner.nextLine();
                System.out.print("请输入放映场次ID：");
                String ownScreeningId = scanner.nextLine();
                Screening screening = currentFrontDesk.listScreenings().stream().filter(s -> s.getScreeningId().equals(ownScreeningId)).findFirst().orElse(null);
                if (screening == null) {
                    System.out.println("未找到对应场次！");
                    return;
                }
                List<Seat> screeningSeats = screening.getSeats();
                if (screeningSeats == null || screeningSeats.isEmpty()) {
                    System.out.println("该场次的座位信息为空或未初始化！");
                    return;
                }
                boolean validTicket = false;
                for (Seat seat : screeningSeats) {
                    if (seat.isOccupied() && ownTicketId.equals(seat.getTicketId())) {
                        validTicket = true;
                        break;
                    }
                }
                if (!validTicket) {
                    System.out.println(" 无效票号！该票号未关联任何已售座位");
                    System.out.println("请检查票号是否正确或联系客服");
                    return;
                }
                System.out.print("请输入座位数量：");
                int seatCount = Integer.parseInt(scanner.nextLine());
                List<Seat> refundSeats = new ArrayList<>();
                for (int i = 0; i < seatCount; i++) {
                    System.out.print("请输入第 " + (i + 1) + " 个座位的行和列（用空格分隔）：");
                    String[] seatInfo = scanner.nextLine().split(" ");
                    int row = Integer.parseInt(seatInfo[0]);
                    int col = Integer.parseInt(seatInfo[1]);
                    Seat actualSeat = screeningSeats.stream().filter(s -> s.getRow() == row && s.getCol() == col).findFirst().orElse(null);
                    if (actualSeat == null) {
                        System.out.println(" 座位[" + row + "," + col + "]不存在！");
                        return;
                    }
                    if (!ownTicketId.equals(actualSeat.getTicketId())) {
                        System.out.println("座位[" + row + "," + col + "]不属于票号 " + ownTicketId);
                        return;
                    }
                    if (!actualSeat.isOccupied()) {
                        System.out.println(" 座位[" + row + "," + col + "]未售出！");
                        return;
                    }
                    refundSeats.add(actualSeat);
                }
                System.out.print("请输入总价格：");
                double ticketPrice = Double.parseDouble(scanner.nextLine());
                System.out.print("请输入购票时间（格式：yyyy-MM-dd HH:mm:ss）：");
                String dateTimeStr = scanner.nextLine();
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                LocalDateTime buyTicketsTime = LocalDateTime.parse(dateTimeStr, formatter);
                Date buyTime = java.sql.Timestamp.valueOf(buyTicketsTime);
                Ticket tempTicket = new Ticket(ownTicketId, screening, refundSeats, seatCount, buyTime, 0, ticketPrice, 0, 0.0);
                LocalDateTime screeningTime = screening.getTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
                LocalDateTime now = LocalDateTime.now();
                Duration beforeStart = Duration.between(now, screeningTime);
                double refundAmount;
                if (beforeStart.toHours() >= 24) {
                    refundAmount = ticketPrice;
                    System.out.println("提前24小时以上退票，可获全款退还");
                } else if (beforeStart.toHours() >= 1) {
                    refundAmount = ticketPrice * 0.9;
                    System.out.println("提前1-24小时退票，扣除10%手续费");
                } else {
                    System.out.println("距离电影开场不足1小时，无法退票！");
                    return;
                }
                for (Seat seat : refundSeats) {
                    seat.setOccupied(false);
                }
                for (Seat seat : refundSeats) {
                    seat.setOccupied(false);
                    System.out.println(" 已释放座位 [" + seat.getRow() + "," + seat.getCol() + "]");
                }
                System.out.println("退票成功！已退还金额：" + refundAmount);
                System.out.println("座位已释放，可重新售卖。");

        }
    }
}


